<?php
/**
 * Created by PhpStorm.
 * User: trnall
 * Date: 2020/10/19
 * Time: 14:51
 */

namespace app\sapi\controller\v1;

use app\common\controller\Api;
use app\api\service\OrderService;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use app\common\model\OrderPay;
use app\common\model\User;
use app\common\model\OrderAftersale;
use app\admin\model\Play as PlayModel;
use app\common\model\Order;
use think\Db;
use think\Exception;
use addons\third\model\Third;
use wechat\wxpay\JsApiPay;
use app\admin\model\Shop;

/**
 * 线上订单
 * Class Order
 * @package app\sapi\controller\v1
 */
class Bill extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        if (isset($this->auth->id) && $this->auth->id) {
            $data = (new User())->get($this->auth->id);
            // 如果没有数据，或账户类型为商户，则返回code为0
            if (!isset($data['user_type']) || $data['user_type']==2) {
                $this->error('用户不是商家角色',$data);
            }
        }

    }

    /**
     * 活动列表，显示商家所有店铺的活动
     */
    public function play_list()
    {
        $page = input('page/d', 1);
        $shop_no = input('bill', '');
        $play_status = input('play_status/d', 9);//'0' => '待支付', '1' => '待审核', '2' => '进行中', '3' => '待结算', '4' => '已结束', '5' => '已完成', '6' => '驳回'9-全部
        $shop = Db::name('shop')->field('logo_pic,shop_no,have_uid,phone,shop_name')->where(['shop_no'=>$shop_no])->find();
        if (!$shop) {
            $this->error('查询不到店铺');
        }
        // 账单生成后才显示那天的活动
        $create_dt = Db::name('bill_list')->order('id desc')->value('create_dt');
        $create_dt = substr($create_dt,0,10);
        // 四种类型的活动
        $list = [
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 1,'scheme_no'=>'图文反馈','play_status'=>$play_status,'shop_type_text'=>'美团'],// 美团图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 1,'scheme_no'=>'无需反馈','play_status'=>$play_status,'shop_type_text'=>'美团'],// 美团无需反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 2,'scheme_no'=>'图文反馈','play_status'=>$play_status,'shop_type_text'=>'饿了么'],// 饿了么图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 2,'scheme_no'=>'无需反馈','play_status'=>$play_status,'shop_type_text'=>'饿了么'],// 饿了么无需反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 3,'scheme_no'=>'图文反馈','play_status'=>$play_status,'shop_type_text'=>'京东'],// 京东图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 3,'scheme_no'=>'无需反馈','play_status'=>$play_status,'shop_type_text'=>'京东'],// 京东无需反馈
        ];
        $is_pay=0;
        if ($play_status==3) {
            $order_status = [3,6,-9];
            $where = ['s.phone'=>$shop['phone'],'po.is_pay'=>$is_pay,'po.order_status'=>['in',$order_status],'po.create_dt'=>['<',$create_dt]];
        } elseif ($play_status==5) {
            $is_pay=1;
            $order_status = [3,-9];
            $where = ['s.phone'=>$shop['phone'],'po.is_pay'=>$is_pay,'po.order_status'=>['in',$order_status]];
        }
        $shopslist = Db::name('shop')->alias('s')->join('chbc_play_order po','po.shop_no=s.shop_no')->field('s.shop_no,s.logo_pic,po.id,s.phone,s.shop_name,LEFT(po.create_dt, 10) as create_dt')->where($where)->group('s.shop_no,create_dt')->page($page,50)->order('create_dt desc')->select();
        $start_time = time();
        $end_time = time();
        $data = [];
        foreach ($shopslist as $k => $v) {
            foreach ($list as $key => $value) {
                $value['img'] = $v['logo_pic'];
                $value['img_url'] = strpos($value['img'],'://')===false?config('upload_domain').$value['img']:$value['img'];
                $value['order_over_num'] = 0;
                $value['acture_total_money'] = 0;
                $orders = Order::where(['shop_no'=>$v['shop_no'],'scheme_no'=>$value['scheme_no'],'platform_no'=>$value['shop_type'],'is_pay'=>$is_pay,'order_status'=>['in',$order_status]])->where('create_dt like "'.$v['create_dt'].'%"')->field('service_charge_amt,actual_rebate_amt,create_dt,place_time')->select();
                if (!$orders) continue;
                foreach ($orders as $kk => $vv) {
                    $value['order_over_num']+=1;
                    $value['acture_total_money']+=$vv['service_charge_amt']+$vv['actual_rebate_amt'];
                    if ($vv['place_time']<$start_time) $start_time=$vv['place_time'];
                    if ($vv['place_time']>$end_time) $end_time=$vv['place_time'];
                }
                $value['acture_total_money']=round($value['acture_total_money'],2);
                if ($value['order_over_num']==0 && $value['acture_total_money']==0) continue;
                $value['start_date_text'] = $v['create_dt'];
                $value['end_date_text'] = $v['create_dt'];
                $value['id'] = $value['shop_type'].'|'.$value['shop_type_text'].'|'.$value['scheme_no'].'|'.$value['order_over_num'].'|'.$value['acture_total_money'].'|'.$value['start_date_text'].'|'.$value['end_date_text'];
                $value['play_no'] = $value['shop_type'].'|'.$value['shop_type_text'].'|'.$value['scheme_no'].'|'.$value['order_over_num'].'|'.$value['acture_total_money'].'|'.$value['start_date_text'].'|'.$value['end_date_text'].'|'.$v['shop_no'];
                $value['shop_name'] = $v['shop_name'];
                $data[] = $value;
            }
        }
        $this->success('活动列表', ['list'=>$data,'total'=>count($data)]);




        // $where = [];
        // $time = strtotime(date('Ymd'));
        // if (in_array($play_status, [0,1,2,3,5,6])) {
        //     $where['play_status'] = ['=',$play_status];
        //     $where['shop_no'] = ['in',$shops];
        //     // 待支付订单列表不包括昨天的活动
        //     if ($play_status==3 && date('H')<13) {
        //         $where['start_date'] = ['<',$time-86400];
        //     } else {
        //         $where['start_date'] = ['<',$time];
        //     }
        //     $list = PlayModel::where($where)->page($page,10)->order('id desc')->select();
        //     $total = PlayModel::where($where)->count();
        //     $data = [];
        //     $sum = 0;
        //     foreach ($list as $k => $v) {
        //         $list[$k]['acture_total_money'] = (float)Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(service_charge_amt+actual_rebate_amt)');
        //         if ($list[$k]['acture_total_money']==0 && $play_status==3) {
        //             continue;
        //         }
        //         $list[$k]['order_over_num'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
        //         $list[$k]['acture_pay'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt)');
        //         $data[] = $list[$k];
        //     }
        //     $list2 = PlayModel::where($where)->order('id desc')->select();
        //     foreach ($list2 as $k2 => $v2) {
        //         $list2[$k2]['acture_total_money'] = (float)Order::where(['play_no'=>$v2['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(service_charge_amt+actual_rebate_amt)');
        //         $sum += $list2[$k2]['acture_total_money'];
        //     }
        //     $this->success('活动列表', ['list'=>$data,'sum'=>$sum,'total'=>$total]);
        // // } elseif ($play_status==3) {
        // //     $where['p.play_status'] = ['in',[3,4]];
        // //     $where['p.shop_no'] = ['in',$shops];
        // //     $list = PlayModel::alias('p')->join('chbc_play_order po','po.play_no=p.play_no and po.order_status=3')->where($where)->page($page,10)->field('p.*')->order('p.id desc')->select();
        // //     foreach ($list as $k => $v) {
        // //         $list[$k]['order_over_num'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>3])->count();
        // //         $list[$k]['acture_pay'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>3])->value('sum(actual_rebate_amt)');
        // //     }
        // //     $this->success('活动列表', $list);
        // }
        // $where['shop_no'] = ['in',$shops];
        // $where['start_date'] = ['<',$time];
        // $list = PlayModel::where($where)->page($page,10)->order('id desc')->select();
        // $total = PlayModel::where($where)->count();
        // $sum = 0;
        // foreach ($list as $k => $v) {
        //     $list[$k]['acture_total_money'] = (float)Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(service_charge_amt+actual_rebate_amt)');
        //     $list[$k]['order_over_num'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
        //     $list[$k]['acture_pay'] = Order::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt)');
        // }
        // $list2 = PlayModel::where($where)->order('id desc')->select();
        // foreach ($list2 as $k2 => $v2) {
        //     $list2[$k2]['acture_total_money'] = (float)Order::where(['play_no'=>$v2['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(service_charge_amt+actual_rebate_amt)');
        //     $sum += $list2[$k2]['acture_total_money'];
        // }
        // $this->success('活动列表', ['list'=>$list,'sum'=>$sum,'total'=>$total]);
    }

    /**
     * 活动详情
     * @DateTime 2023-03-22T19:31:58+0800
     * @return   [type]                   [description]
     */
    public function play_info()
    {
        $id = input('id', '');
        $arr = explode('|', $id);
        $play = [];
        $play['shop_type'] = $arr[0];
        $play['shop_type_text'] = $arr[1];
        $play['scheme_no'] = $arr[2];
        $play['num'] = $arr[3];
        $play['shop_settlement'] = $arr[4];
        $play['start_date_text'] = $arr[5];
        $play['end_date_text'] = $arr[6];
        $play['play_status'] = 3;
        $this->success('活动详情', $play);



        // $id = input('id/d', 0);
        // $where = [];
        // $where['id'] = $id;
        // $play = PlayModel::where($where)->find();
        // if (empty($play)) $this->error('活动不存在');
        // $play['order_over_num'] = Order::where(['play_no'=>$play['play_no'],'order_status'=>3])->count();
        // $play['acture_pay'] = Order::where(['play_no'=>$play['play_no'],'order_status'=>3])->value('sum(actual_rebate_amt)');
        // $this->success('活动详情', $play);
    }


    public function order_list()
    {
        $pageSize = 20;
        $page = input('page/d', 1);
        // $shop_no = input('bill/d', '');
        $order_status = input('order_status/d', 0);//0 全部 1 待上传 2 审核中  3 已完成
        $platform_no = input('platform_no/d', 0);
        $scheme_no = input('scheme_no', '');
        $play_no = input('play_no','');
        if (!$platform_no || !$scheme_no || !$play_no) $this->error('参数有误');
        $arr = explode('|', $play_no);
        // $shop = Db::name('shop')->where(['shop_no'=>$shop_no])->field('phone')->find();
        // $shop_no = Db::name('shop')->where('phone',$shop['phone'])->value('group_concat(shop_no)');
        $shop_no = $arr[7];
        $where = ['scheme_no' => $scheme_no,'shop_no'=>$shop_no,'platform_no'=>$platform_no];
        switch ($order_status) {
            case 0:
                //  只显示已完成的订单
                $where['order_status'] = ['in',[3,6,-9]];
                break;
            case 1:
                $where['order_status'] = 1;
                break;
            case 2:
                $where['order_status'] = 2;
                break;
            case 3:
                $where['order_status'] = 3;
                break;
            default:
                break;
        }
        $OrderModel = new Order();
        $data = $OrderModel->with(['shop'])
            ->where($where)
            ->where('create_dt like "'.$arr[5].'%"')
            ->order('id DESC')
            ->select();
        foreach ($data as $key => &$value) {
            $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id DESC')->find();
            if ($value['is_yunzhan']==0) {
                $value['proof']['one_image_url'] = strpos($value['proof']['one_image'],'://')===false?config('chbc_upload_domain').$value['proof']['one_image']:$value['proof']['one_image'];
                $value['proof']['two_image_url'] = strpos($value['proof']['two_image'],'://')===false?config('chbc_upload_domain').$value['proof']['two_image']:$value['proof']['two_image'];
                $value['proof']['three_image_url'] = strpos($value['proof']['three_image'],'://')===false?config('chbc_upload_domain').$value['proof']['three_image']:$value['proof']['three_image'];
            } else {
                $value['proof']['one_image_url'] = strpos($value['proof']['one_image'],'://')===false?config('domain').$value['proof']['one_image']:$value['proof']['one_image'];
                $value['proof']['two_image_url'] = strpos($value['proof']['two_image'],'://')===false?config('domain').$value['proof']['two_image']:$value['proof']['two_image'];
                $value['proof']['three_image_url'] = strpos($value['proof']['three_image'],'://')===false?config('domain').$value['proof']['three_image']:$value['proof']['three_image'];
            }
        }
        $this->success('', $data);
    }

    /**
     * 店铺详细
     * @DateTime 2023-03-22T10:38:28+0800
     * @return   [type]                   [description]
     */
    public function shopDetail()
    {
        $shop_no = input('bill', '');
        if (!$shop_no) {
            $this->error('缺少参数');
        }
        $where = [];
        $where['s.shop_status'] = ['=',1];
        $where['s.delete_dt'] = ['null',''];
        $where['s.shop_no'] = ['=',$shop_no];
        $info = Shop::where($where)->alias('s')->field('s.*,sp.qrcode_pic,sp.qrcode_pic as qrcode_pic_url,sp.platform_no')->join('chbc_shop_platform sp','sp.shop_no=s.shop_no')->find();
        // 店名用后台商家列表关联的店铺名称
        $shops = Db::name('user')->alias('u')->join('chbc_shop s','s.shop_no=u.shop_no')->field('s.*')->where(['u.id'=>$info['have_uid']])->find();
        if (isset($shops['shop_name']) && $shops['shop_name']) {
            $info['shop_name'] = $shops['shop_name'];
        }
        $info['qrcode_pic_url'] = strpos($info['qrcode_pic_url'],'://')===false?config('upload_domain').$info['qrcode_pic_url']:$info['qrcode_pic_url'];
        $this->success('店铺详情', $info);
    }


    public function isPaying()
    {
        if (!isset($this->auth->id)) {
            $this->error('请先登录');
        }
        $user_id = $this->auth->id;
        // $user_id =23;
        $play_no = input('play_no','', 'strip_tags,htmlspecialchars');
        $play_order_no = input('play_order_no','', 'strip_tags,htmlspecialchars');
        $pay_type = input('pay_type/d',0); // 1-微信2-支付宝
        if (!$play_no && !$play_order_no) {
            $this->error('缺少参数');
        }
        if ($play_no) {
            if (strpos($play_no,',')!==false) {
                $list = explode(',', $play_no);
                $order = [];
                foreach ($list as $key => $value) {
                    $arr = explode('|', $value);
                    $platform_no = $arr[0];
                    $scheme_no = $arr[2];
                    $shop_no = $arr[7];
                    $create_dt = $arr[5];
                    $where = ['platform_no' => $platform_no,'scheme_no' => $scheme_no,'shop_no'=>$shop_no,'order_status' => ['in',[3,6,-9]]];
                    // 判断当前活动有没有
                    $OrderModel = new Order();
                    $orders = $OrderModel->where($where)
                    ->where('create_dt like "'.$create_dt.'%" and is_pay=0')
                    ->field('play_order_no,actual_rebate_amt,service_charge_amt')->select();
                    $order = array_merge($order,$orders);
                }
            } else {
                $arr = explode('|', $play_no);
                $platform_no = $arr[0];
                $scheme_no = $arr[2];
                $shop_no = $arr[7];
                $create_dt = $arr[5];
                $where = ['platform_no' => $platform_no,'scheme_no' => $scheme_no,'shop_no'=>$shop_no,'order_status' => ['in',[3,6,-9]]];
                // 判断当前活动有没有
                $OrderModel = new Order();
                $order = $OrderModel->where($where)
                ->where('create_dt like "'.$create_dt.'%" and is_pay=0')
                ->field('play_order_no,actual_rebate_amt,service_charge_amt')->select();
            }
            if (!$order) $this->error('未查询到订单');
            $rebate_amt = 0;
            $all = [];
            $play_order_no = '';
            foreach ($order as $k => $v) {
                $rebate_amt += round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
                $play_order_no .= $v['play_order_no'].',';
            }
            // $rebate_amt = 0.1;
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => $rebate_amt,
                'pay_time' => time(),
                'play_nos' => trim($play_order_no,','),
            ];
        } elseif ($play_order_no) {
            $play_order_nos = explode(',', $play_order_no);
            if (!$play_order_nos) {
                $this->error('参数错误');
            }
            // 判断当前活动有没有
            $OrderModel = new Order();
            $where= [];
            $where['play_order_no'] = ['in',$play_order_nos];
            // $where['user_id'] = $user_id;
            $order = $OrderModel->where($where)->select();
            if (!$order) $this->error('未查询到相关数据');
            $rebate_amt = 0;
            $all = [];
            foreach ($order as $k => $v) {
                if (!in_array($v['order_status'], [3,6,-9]) || $v['is_pay']!=0) {
                    $this->error('活动状态有误');
                }
                $rebate_amt += round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
            }
            // $rebate_amt = 0.1;
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => $rebate_amt,
                'pay_time' => time(),
                'play_nos' => $play_order_no,
            ];
        }
        $pay = OrderPay::where(['user_id'=>$user_id,'play_nos'=>$pay_data['play_nos']])->order('id DESC')->find();
        if (isset($pay['pay_time']) && time()-$pay['pay_time']<10) {
            $this->success('您近期支付过该订单，请确认是否继续支付？',['status'=>0]);
        }
        $this->success('支付中',['status'=>1]);
    }


    /**
     * 账单支付
     * @DateTime 2023-04-24T21:35:16+0800
     * @return   [type]                   [description]
     */
    public function payBill()
    {
        if (!isset($this->auth->id)) {
            $this->error('请先登录');
        }
        $user_id = $this->auth->id;
        // $user_id =23;
        $play_no = input('play_no','', 'strip_tags,htmlspecialchars');
        $play_order_no = input('play_order_no','', 'strip_tags,htmlspecialchars');
        $pay_type = input('pay_type/d',0); // 1-微信2-支付宝
        if (!$play_no && !$play_order_no) {
            $this->error('缺少参数');
        }
        if ($play_no) {
            if (strpos($play_no,',')!==false) {
                $list = explode(',', $play_no);
                $order = [];
                foreach ($list as $key => $value) {
                    $arr = explode('|', $value);
                    $platform_no = $arr[0];
                    $scheme_no = $arr[2];
                    $shop_no = $arr[7];
                    $create_dt = $arr[5];
                    $where = ['platform_no' => $platform_no,'scheme_no' => $scheme_no,'shop_no'=>['in',explode(',', $shop_no)],'order_status' => ['in',[3,6,-9]]];
                    // 判断当前活动有没有
                    $OrderModel = new Order();
                    $orders = $OrderModel->where($where)
                    ->where('create_dt like "'.$create_dt.'%" and is_pay=0')
                    ->field('play_order_no,actual_rebate_amt,service_charge_amt,play_no,shop_no')->select();
                    $order = array_merge($order,$orders);
                }
            } else {
                $arr = explode('|', $play_no);
                $platform_no = $arr[0];
                $scheme_no = $arr[2];
                $shop_no = $arr[7];
                $create_dt = $arr[5];
                $where = ['platform_no' => $platform_no,'scheme_no' => $scheme_no,'shop_no'=>['in',explode(',', $shop_no)],'order_status' => ['in',[3,6,-9]]];
                // 判断当前活动有没有
                $OrderModel = new Order();
                $order = $OrderModel->where($where)
                ->where('create_dt like "'.$create_dt.'%" and is_pay=0')
                ->field('play_order_no,actual_rebate_amt,service_charge_amt,play_no,shop_no')->select();
            }
            if (!$order) $this->error('未查询到订单');
            $rebate_amt = 0;
            $all = [];
            $play_order_no = '';
            // 计算经纪人佣金
            // $shopyj = [];
            // $yj = [];
            $yjsum = 0;
            foreach ($order as $k => $v) {
                $rebate_amt += round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
                $play_order_no .= $v['play_order_no'].',';
                // 计算经纪人佣金
                if (!isset($shopyj[$v['shop_no']])) {
                    $shop = Db::name('shop')->where(['shop_no'=>$v['shop_no']])->field('middleman_id,shop_no')->find();
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id,ledger_no')->find();
                    // if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                    //     if (isset($yj[$middleman['ledger_no']])) {
                    //         $yj[$middleman['ledger_no']]+=$middleman['rebate_amt'];
                    //     } else {
                    //         $yj[$middleman['ledger_no']]=$middleman['rebate_amt'];
                    //     }
                    //     $shopyj[$v['shop_no']] = $middleman['rebate_amt'];
                    // }
                } else {
                    // $yj[$middleman['ledger_no']] += $shopyj[$v['shop_no']];
                }
            }
            // foreach ($yj as &$y) {
            //     $y=0.01;
            //     $yjsum+=$y;
            // }
            // if (round($yjsum,2)>=$rebate_amt) $this->error('佣金计算错误');
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => $rebate_amt,
                'pay_time' => time(),
                'play_nos' => trim($play_order_no,','),
            ];
            foreach ($order as $key => $value) {
                $all[$key]['pay_no'] = $pay_data['pay_no'];
                $all[$key]['play_no'] = $value['play_no'];
                $all[$key]['play_order_no'] = $value['play_order_no'];
            }
        } elseif ($play_order_no) {
            $play_order_nos = explode(',', $play_order_no);
            if (!$play_order_nos) {
                $this->error('参数错误');
            }
            // 判断当前活动有没有
            $OrderModel = new Order();
            $where= [];
            $where['play_order_no'] = ['in',$play_order_nos];
            // $where['user_id'] = $user_id;
            $order = $OrderModel->where($where)->select();
            if (!$order) $this->error('未查询到相关数据');
            $rebate_amt = 0;
            $all = [];
            $yjsum = 0;
            foreach ($order as $k => $v) {
                if (!in_array($v['order_status'], [3,6,-9]) || $v['is_pay']!=0) {
                    $this->error('活动状态有误');
                }
                $rebate_amt += round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
                // 计算经纪人佣金
                $shopyj = [];
                $yj = [];
                if (!isset($shopyj[$v['shop_no']])) {
                    $shop = Db::name('shop')->where(['shop_no'=>$v['shop_no']])->field('middleman_id,shop_no')->find();
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id,ledger_no')->find();
                    // if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                    //     if (isset($yj[$middleman['ledger_no']])) {
                    //         $yj[$middleman['ledger_no']]+=$middleman['rebate_amt'];
                    //     } else {
                    //         $yj[$middleman['ledger_no']]=$middleman['rebate_amt'];
                    //     }
                    //     $shopyj[$v['shop_no']] = $middleman['rebate_amt'];
                    // }
                } else {
                    // $yj[$middleman['ledger_no']] += $shopyj[$v['shop_no']];
                }
            }
            // foreach ($yj as &$y) {
            //     $y=0.01;
            //     $yjsum+=$y;
            // }
            // if (round($yjsum,2)>=$rebate_amt) $this->error('佣金计算错误');
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => round($rebate_amt,2),
                'pay_time' => time(),
                'play_nos' => $play_order_no,
            ];
            foreach ($order as $key => $value) {
                $all[$key]['pay_no'] = $pay_data['pay_no'];
                $all[$key]['play_no'] = $value['play_no'];
                $all[$key]['play_order_no'] = $value['play_order_no'];
            }
        }
        // $rebate_amt = 0.1;
        Db::startTrans();
        try {
            // $pay = OrderPay::where(['user_id'=>$user_id,'play_nos'=>$play_order_no])->find();
            // if (isset($pay['create_dt']) && time()-strtotime($pay['create_dt'])<10) {
            //     $this->error('您近期支付过该订单，请确认是否继续支付？');
            // }
            if (isset($pay_data) && $pay_data) {
                OrderPay::create($pay_data);
            }
            if (isset($all) && $all) {
                Db::name('order_pay_item')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write('支付账单：'.$e->getMessage());
            $this->error('支付有误');
        }

        $config = get_addon_config('epay');
        if ($pay_data['pay_mod']=='alipay') {
            $params = [
                'amount'=>$rebate_amt,
                'orderid'=>$pay_data['pay_no'],
                'type'=>$pay_data['pay_mod'],
                'title'=>"商家支付账单",
                'method'=>"wap",
                'notifyurl'=>request()->root(true) . $config['alipay']['notify_url'],
                'returnurl'=>request()->root(true) . $config['alipay']['return_url'],
            ];
            $YopService = new \services\YopService();
            $divide_detail = [];
            // foreach ($yj as $key1 => $value1) {
            //     $divide_detail[] = [
            //         'amount' => $value1,
            //         'ledgerNo' => $key1,
            //         'divideDetailDesc' => '经纪人收益',
            //     ];
            // }
            $res = $YopService->prePay('ALIPAY','USER_SCAN',$pay_data['pay_no'],$rebate_amt,'',$_SERVER['REMOTE_ADDR'],$divide_detail,round($rebate_amt-$yjsum,2));
        } elseif ($pay_data['pay_mod']=='wechat') {
            $openid = User::where('id',$user_id)->value('openid');
            // $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'h5'])->value('openid');
            $params = [
                'amount'=>$rebate_amt,
                'orderid'=>$pay_data['pay_no'],
                'type'=>'wechat',
                'title'=>"商家支付账单",
                'method'=>"mp",
                'notifyurl'=>request()->root(true) . $config['wechat']['notify_url'],
                'openid'=>$openid,
            ];
            $YopService = new \services\YopService();
            $divide_detail = [];
            // foreach ($yj as $key1 => $value1) {
            //     $divide_detail[] = [
            //         'amount' => $value1,
            //         'ledgerNo' => $key1,
            //         'divideDetailDesc' => '经纪人收益',
            //     ];
            // }
            $res = $YopService->prePay('WECHAT','WECHAT_OFFIACCOUNT',$pay_data['pay_no'],$rebate_amt,$openid,$_SERVER['REMOTE_ADDR'],$divide_detail,round($rebate_amt-$yjsum,2));
            $res = json_decode($res,1);
            // $res = \addons\epay\library\Service::submitOrder($params);
            $this->success('',$res);
        }
        $this->success('',[$res]);
    }
}